package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC698 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public boolean canPartitionKSubsets(int[] arr, int k) {
            boolean[] visited = new boolean[arr.length];
            int sum = 0;
            for (int num : arr) {
                sum += num;
            }
            return canPartitionKSubsetsRecur(arr, k, 0, 0, sum / k, visited);
        }

        public boolean canPartitionKSubsetsRecur(int[] arr, int k, int start, int curSum, int tartNum, boolean[] visited) {
            if (k == 0) return true;
            if (curSum == tartNum) {
                return canPartitionKSubsetsRecur(arr, k - 1, 0, 0, tartNum, visited);
            }
            for (int i = start; i < arr.length; i++) {
                if (visited[i]) continue;
                if (arr[i] > tartNum) return false;
                if (arr[i] + curSum <= tartNum) {
                    visited[i] = true;
                    if (canPartitionKSubsetsRecur(arr, k, i + 1, curSum + arr[i], tartNum, visited)) return true;
                    visited[i] = false;
                }
            }

            return false;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] nums = InputUtil.toIntegerArray("[4, 3, 2, 3, 5, 2, 1]");
        int k = 4;
        System.out.println(solution.canPartitionKSubsets(nums, k));
    }

    public static void main(String[] args) throws Exception {
        LC698 an = new LC698();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
